var WebSocketServer = require('websocket').server;
var http = require('http');
const MockJS = require('mockjs');

// 创建 http 服务器
var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(8080, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

// 基于 http 服务器创建 WebSocket 服务器
wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed.
  return true;
}

/**
 * 生成随机订单
 */
function generateRandomOrder() {
  // 模拟订单数据
  return MockJS.mock({
    'orderId': '@id',
    'customerName': '@cname',
    'address': '@county(true)',
    'title': '@ctitle(5, 10)', // 不代表有实际语义
    'price': '@float(100, 2000, 0, 2)',
    'date': Date.now(),
    'status': '@integer(0, 3)'
  });
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }
    
    // 等待客户端的连接
    var connection = request.accept('echo-protocol', request.origin);

    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message) {
      if (message.type === 'utf8') {
        console.log('Received Message: ' + message.utf8Data);
        connection.sendUTF(message.utf8Data);
      }
      else if (message.type === 'binary') {
        console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
        connection.sendBytes(message.binaryData);
      }
    });
    connection.on('close', function(reasonCode, description) {
      console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });

    // 每隔一段时间，生成一条随机的订单数据，发送给前端
    function randomOrder() {
      var order = generateRandomOrder();
      connection.sendUTF(JSON.stringify(order));
      // 随机5-15秒的时间生成一条数据
      const time = Math.floor(Math.random() * (15 - 5 + 1)) + 5;

      setTimeout(randomOrder, time * 1000);
    }
    randomOrder()
});
